package com.example.security.service.impl;

import com.example.security.entity.User;
import com.example.security.mapper.UserMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

/**
 * @Author: oyc
 * @Date: 2019/1/29 14:19
 * @Description: 用户服务类
 */
@Service
@Slf4j
public class UserDetailsServiceImpl<T extends User> implements UserDetailsService {

    @Resource
    private UserMapper userMapper;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        try {
            User user = userMapper.findByUserName(username);
            if (user == null) {
                throw new UsernameNotFoundException("用户名不存在");
            }

            //用户权限
            List<SimpleGrantedAuthority> authorities = new ArrayList<>();
            if (!StringUtils.isEmpty(user.getRoles())) {
                log.info("user.getRoles() ========= " + user.getRoles());
                String[] roles = user.getRoles().split(",");
                for (String role : roles) {
                    if (!StringUtils.isEmpty(role)) {
                        authorities.add(new SimpleGrantedAuthority(role.trim()));
                    }
                }
            }

            //String username, String password, boolean enabled, boolean accountNonExpired,
            //			boolean credentialsNonExpired, boolean accountNonLocked,
            //			Collection<? extends GrantedAuthority> authorities

            return new org.springframework.security.core.userdetails.User(
                    user.getUsername(),
                    user.getPassword(),
                    user.isEnabled(),
                    user.isAccountNonExpired(),
                    user.isCredentialsNonExpired(),
                    user.isAccountNonLocked(),
                    authorities
            );
        } catch (Exception e) {
            log.error("loadUserByUsername()", e);
            throw new UsernameNotFoundException("用户名不存在");
        }

    }

}